<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="4">
        <div class="left">
          <div class="title">商品分类列表</div>
          <div class="tree">
            <TreeProduct @sendTreeData="sendTreeData"></TreeProduct>
          </div>
        </div>
      </el-col>
      <el-col :span="20">
        <div class="wrapper">
          <div class="title">商品{{ title }}</div>
          <div class="form">
            <el-form :rules="rules" ref="ruleForm" :model="ruleForm" label-width="100px">
              <el-form-item label="所属分类" prop="catagory">
                <span> {{ ruleForm.category }}</span>
              </el-form-item>
              <el-form-item label="商品名称" prop="title">
                <el-input v-model="ruleForm.title" size="small"></el-input>
              </el-form-item>
              <el-form-item label="商品价格" prop="price">
                <el-input v-model="ruleForm.price" size="small"></el-input>
              </el-form-item>
              <el-form-item label="商品数量" prop="num">
                <el-input v-model="ruleForm.num" size="small"></el-input>
              </el-form-item>
              <el-form-item label="商品卖点" prop="sellPoint">
                <el-input v-model="ruleForm.sellPoint" size="small"></el-input>
              </el-form-item>
              <!-- <el-form-item label="商品图片" prop="image">
                <UploadImg @sendImg="sendImg" ref="uploadImg" :fileList="fileList"></UploadImg>
              </el-form-item> -->
              <el-form-item label="商品描述" prop="descs">
                <WangEditor @sendWangEditor="sendWangEditor" ref="wangEditor"></WangEditor>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" v-show="title != '详情'" @click="submitForm('ruleForm')">提交</el-button>
                <el-button type="primary" v-show="title != '详情'" @click="resetForm('ruleForm')">重置</el-button>
                <el-button type="info" @click="closePage">取消</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import TreeProduct from './TreeProduct.vue';
import UploadImg from './UploadImg.vue';
import WangEditor from './WangEditor.vue';
export default {
  components: { TreeProduct,UploadImg,WangEditor},
  data() {
    return {
      fileList:[], //图片容器集合
      ruleForm: { //表单数据
        id:'',
        title: '',
        num: '',
        price: '',
        sellPoint: '',
        image: [],
        descs: '',
        category:'',
        cid: '', //商品id  id是类目id
        isShow: true,
      },
      rules: {// 表单验证规则
        category: [
          { required: true, message: '请输入商品类目' }
        ],
        title: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        num: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
      }
    }
  },
  methods: {
    //获取子组件tree数据
    sendTreeData(data,node){
      // data为tree的当前节点数据 node中包含父节点数据
      let str = node.data.name
      // //console.log(node);
      if(node.parent.data){ //父节点存在，则进行节点的拼接
        str = node.parent.data.name + '/' + node.data.name
      }
      ////console.log(str);
      this.ruleForm.category = str
      this.ruleForm.cid = data.cid
    },
    //获取子组件上传图片组件中的图片地址
    sendImg(url){
      // 此处image是一个数组，往数组中放数据，需要用push方法
      this.ruleForm.image.push(url)
      //console.log('获取子组件图片位置')
    },
    //获取WangEditor子组件的数据
    sendWangEditor(val){
      this.ruleForm.descs = val
      ////console.log('获取富文本编辑器中的内容',val)
    },
    //添加商品
    async insertTbItem(params){
      let res = await this.$api.insertTbItem(params)
      // //console.log('添加成功',res)
      if(res.data.status === 200){
        this.$message({
          message: '添加商品成功',
          type: 'success'
        });
        this.$router.push('/product/list')
      } else {
        //错误信息提示
        this.$message.error('错了哦，添加商品失败');
      }
    },
    //修改商品
    async updateTbItem(params){
      let res = await this.$api.updateTbItem(params)
      if(res.data.status === 200){
        this.$message({
          message: '修改商品成功',
          type: 'success'
        });
        this.$router.push('/product/list')
      }
    },
     //提交表单
     submitForm(formName) { 
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let { id,title, cid, category, sellPoint, price, num, descs, image } = this.ruleForm
            if(this.title==="添加"){ 
             this.insertTbItem({title, image:JSON.stringify(image),sellPoint, price, cid, category, num, descs})
            } else { //修改
              //console.log('id',id);
              this.updateTbItem({id,title, image:JSON.stringify(image),sellPoint, price, cid, category, num, descs})
            }          
          } else {
            //console.log('error submit!!');
            return false;
          }
        });
      },
    //重置表单
    resetForm(formName) { 
      if(this.title === '添加'){
        this.$refs[formName].resetFields()
        // 图片列表
        this.$refs.uploadImg.clear()
        // wangeditor
        this.$refs.wangEditor.editor.clear()
      } else {
          //编辑页面--重置操作 回归到未修改前的状态
        let rowData = JSON.parse(JSON.stringify(this.rowData))
        //console.log('rowData',rowData);
        this.ruleForm = rowData
        let imgs = rowData.image //字符串类型
        // let arr = JSON.parse(imgs) //转数组
        this.ruleForm.image = arr
        this.fileList = []
        // arr.forEach(ele => {
        //   this.fileList.push({name:'',url:ele})
        // });
         // 将wangeditor中的html重新赋值，并等待dom加载完毕执行，延迟加载
        this.$nextTick(()=>{
          this.$refs.wangEditor.html = rowData.descs
        })
      }
     
    },
    //取消按钮
    closePage(){
      this.$router.push('/product/list')
    }
  },
  computed:{
    ...mapState('product',['rowData','title'])
  },
  mounted(){
    // 进入页面，读取vuex中的要编辑的数据
    if(this.title == '编辑' || this.title == '详情'){
      //浅拷贝：两个对象数组间的赋值，是复制地址
      this.ruleForm = JSON.parse(JSON.stringify(this.rowData))
      let imgs = this.rowData.image //字符串类型
      let arr = imgs.split("")//转数组
      console.log('this.ruleForm.image1111',arr);
      this.ruleForm.image = arr
      arr.forEach(ele => {
        this.fileList.push({name:'',url:ele})
      });
      console.log(this.fileList);

      // 将wangeditor中的html重新赋值，并等待dom加载完毕执行，延迟加载
      this.$nextTick(()=>{
        this.$refs.wangEditor.html = this.rowData.descs
      })
    }
  }
}
</script> 

<style lang="less" scoped>
.left {
  height: 600px;
  background-color: #fff;

  .title {
    background-color: skyblue;
    padding: 20px;
    color: white;
  }

  .tree {
    padding: 20px;
  }
}

.wrapper {
  // height: 800px;
  background-color: #fff;

  .title {
    background-color: #eee;
    padding: 14px;
    color: #333;
    font-weight: bold;
  }

  .form {
    padding: 30px;
  }
  span {
    color:#333;
  }
}</style>
